package SA.teacher.daily;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import SA.teacher.*;
import SA.teacher.answer.AnswerActivity1;
import SA.teacher.manage.ManageActivity1;
import SA.teacher.notice.NoticeActivity1;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class DailyActivity1 extends Activity {

	ArrayList<TextView> list;
	TextView calendarTitle;
	int firstDay;
	int totDays;
	int iYear;
	int iMonth;
	String id;
	static String day = null;

	String rcvclassid;
	/** Called when the activity is first created.*/
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.daily1);

		Intent intent = getIntent();
		id = intent.getStringExtra("ID");

		Calendar calendar = Calendar.getInstance();
		iYear = calendar.get(Calendar.YEAR);
		iMonth = calendar.get(Calendar.MONTH);
		calendarTitle = (TextView) findViewById(R.id.today);
		list = new ArrayList<TextView>();

		Calendar today = Calendar.getInstance();
		int whatDay = today.get(Calendar.DAY_OF_WEEK);

		int tempday = whatDay % 7;
		switch (tempday) // 0~6까지 토~금요일로 표시
		{
		case 0:
			day = "토";
			break;
		case 1:
			day = "일";
			break;
		case 2:
			day = "월";
			break;
		case 3:
			day = "화";
			break;
		case 4:
			day = "수";
			break;
		case 5:
			day = "목";
			break;
		case 6:
			day = "금";
			break;
		}// end switch


		TableLayout table = (TableLayout) findViewById(R.id.calendar);

		int i, j;
		for (i = 0; i < 6; i++) {
			TableRow tr = new TableRow(this);
			for (j = 0; j < 7; j++) {
				TextView tv = new TextView(this);
				if (j == 0)
					tv.setTextColor(Color.RED);
				else if (j == 6)
					tv.setTextColor(Color.BLUE);
				else
					tv.setTextColor(Color.BLACK);
				tv.setTextSize(25);
				tv.setGravity(Gravity.CENTER_HORIZONTAL);
				tr.addView(tv);
				list.add(tv);
			}
			table.addView(tr);
		}
		table.setStretchAllColumns(true);
		setCalendar(iYear, iMonth);

		//////////////달력 좌우  Button////////////////////////////////////
		ImageView preBtn = (ImageView) findViewById(R.id.pre);
		preBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				iMonth--;
				if (iMonth <= 0) {
					iYear--;
					iMonth = 11;
				}
				setCalendar(iYear, iMonth);
			}
		});

		ImageView nextBtn = (ImageView) findViewById(R.id.next);
		nextBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				iMonth++;
				if (iMonth >= 12) {
					iMonth = 0;
					iYear++;
				}
				setCalendar(iYear, iMonth);
			}
		});


		//////////////Button action////////////////////////////////////
		TextView noticeBtn = (TextView) findViewById(R.id.notice);
		noticeBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				noticeActivity();
			}
		});
		
		ImageView mainBtn = (ImageView) findViewById(R.id.mainBtn);
		mainBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mainActivity();
			}
		});
		
		ImageView manageBtn = (ImageView) findViewById(R.id.manageBtn);
		manageBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				manageActivity();
			}
		});
		
		ImageView answerBtn = (ImageView) findViewById(R.id.answerBtn);
		answerBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				answerActivity();	
			}
		});
	}

	private class classidparse implements Runnable {
		public void run() {
			// TODO Auto-generated method stub
			try {
				
				URL url = new URL("Http://220.67.128.8/dayclassid.php?id="+URLEncoder.encode(id,"EUC-KR"));

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();

				InputStream  is   = null;
				ByteArrayOutputStream baos = null; 
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
					is = conn.getInputStream();  
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];    byte[] byteData = null; 
					int nLength = 0;
					while((nLength = is.read(byteBuffer)) > 0) {   
						baos.write(byteBuffer, 0, nLength); 
					}
					byteData = baos.toByteArray(); 
					String response = new String(byteData, "euc-k-r");   
					rcvclassid =response;
					if(response==null || response.equals("")) {    
						throw new Exception("Response is NULL!");  
					}
				}
				else{
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}
	private class dayclassidparse implements Runnable {
		public void run() {
			// TODO Auto-generated method stub
			try {
				//String addr ="Http://220.67.128.8/temp.php?useUnicode=true&characterEncoding=EUC-KR&tID=1234" + "&adate=20120902" +  "&classid="+  classid + "&content="+content;

				URL url = new URL("Http://220.67.128.8/dailyclassid.php?id="+URLEncoder.encode(id,"EUC-KR")+ "&day=" +URLEncoder.encode(day,"EUC-KR"));
			
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();

				InputStream  is   = null;
				ByteArrayOutputStream baos = null; 
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) { 
					is = conn.getInputStream();  
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];    byte[] byteData = null; 
					int nLength = 0;
					while((nLength = is.read(byteBuffer)) > 0) {   
						baos.write(byteBuffer, 0, nLength); 
					}
					byteData = baos.toByteArray(); 
					String response = new String(byteData, "euc-k-r");   
					rcvclassid =response;
					if(response==null || response.equals("")) {    
						throw new Exception("Response is NULL!");  
					}
				}
				else{
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}


	private void setCalendar(final int year, final int month) {
		Calendar todayCalendar = Calendar.getInstance();
		int todayYear;
		int todayMonth;
		int todayDate;

		todayYear = todayCalendar.get(Calendar.YEAR);
		todayMonth = todayCalendar.get(Calendar.MONTH);
		todayDate = todayCalendar.get(Calendar.DATE);

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		calendar.set(Calendar.DAY_OF_MONTH, 1);

		calendarTitle.setText(year + "년" + (month + 1) + "월");

		int whatDay = calendar.get(Calendar.DAY_OF_WEEK);
		int i;
		int j = 1;

		for (i = whatDay - 1; i < calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + whatDay - 1; i++) {
			if ((year == todayYear) && (month == todayMonth)&& (j == todayDate)) {
				list.get(i).setBackgroundColor(Color.rgb(185, 225, 255));
			}else{
				list.get(i).setBackgroundColor(Color.WHITE);
			}
			list.get(i).setText(j++ + "");

			final int today = j;
			final int tempi=i;
			list.get(i).setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					int tempday=tempi%7;

					switch(tempday) // 0~6까지 토~금요일로 표시
					{
					case 0:
						day = "일";
						break;
					case 1:
						day = "월";
						break;
					case 2:
						day = "화";
						break;
					case 3:
						day = "수";
						break;
					case 4:
						day = "목";
						break;
					case 5:
						day = "금";
						break;
					case 6:
						day = "토";
						break;
					}// end switch      



					dayclassidparse cidps = new dayclassidparse();
					cidps.run();
					final String[] classes = rcvclassid.split(",");
					AlertDialog.Builder bld = new AlertDialog.Builder(DailyActivity1.this);
					bld.setTitle("반을 선택해주세요.")

					.setItems(classes,new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog,	int which) {
							String dailyInfoStr;
							Intent intent = new Intent(DailyActivity1.this, DailyToday2.class);
							dailyInfoStr =  Integer.toString(year) + "-" + Integer.toString(month + 1) + "-" + Integer.toString(today - 1) + "," + classes[which];
							intent.putExtra("dailyInfo",dailyInfoStr);

							intent.putExtra("ID",id);
							startActivity(intent);
						}
					}).show();
				}
			});
		}
	}

	//////////////Button 함수들////////////////////////////////////
	void noticeActivity() {
		Intent intent = new Intent(this, NoticeActivity1.class);
		intent.putExtra("ID",id);
		startActivity(intent);
	}
	void mainActivity() {
		Intent intent = new Intent(this, MainActivity.class);
		intent.putExtra("ID",id);
		startActivity(intent);
	}
	void manageActivity() {
		classidparse cidps = new classidparse();
		cidps.run();
		final String[] classes = rcvclassid.split(",");
		if(classes.length-1!=0){
			new AlertDialog.Builder(DailyActivity1.this)
			.setTitle("반을 선택해주세요.")
			.setItems(classes, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog,	int which) {
					Intent intent = new Intent(DailyActivity1.this, ManageActivity1.class);
					intent.putExtra("ID",id);
					intent.putExtra("classname",classes[which]);
					startActivity(intent);
				}
			}).show();
		}
		else{
			new AlertDialog.Builder(DailyActivity1.this)
			.setMessage("현재 담당하는 반이 없습니다.")
			.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// TODO Auto-generated method stub
				}
			}).show();
		}
	}
	void answerActivity() {
		Intent intent = new Intent(this, AnswerActivity1.class);
		intent.putExtra("ID",id);
		startActivity(intent);
	}

	//////////////뒤로가기 종료////////////////////////////////////
	public boolean onKeyDown(int keyCode, KeyEvent event){
		switch(keyCode){
		case KeyEvent.KEYCODE_BACK:
			String alertTitle = getResources().getString(R.string.app_name);
			String buttonMessage = getResources().getString(R.string.alert_msg_exit);
			String buttonYes = getResources().getString(R.string.button_yes);
			String buttonNo = getResources().getString(R.string.button_no);

			new AlertDialog.Builder(DailyActivity1.this)
			.setTitle(alertTitle)
			.setMessage(buttonMessage)
			.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					moveTaskToBack(true);
					finish();
				}
			})
			.setNegativeButton(buttonNo, null)
			.show();
		}
		return true;
	}
}